package main

import (
	"cat/lb/discover"
	"cat/proto/pb"
	"context"
	"flag"
	"fmt"
	"google.golang.org/grpc"
	"log"
	"net"
	"os"
	"os/signal"
	"syscall"
	"time"
)

var (
	serv = flag.String("service", "hello_service", "service name")
	port = flag.Int("port", 50001, "listening port")
	reg  = flag.String("reg", "http://127.0.0.1:2379", "register etcd address")
)

type Greeter struct {
}

func (s *Greeter) SayHello(ctx context.Context, rep *pb.HelloRequest) (*pb.HelloReply, error) {
	fmt.Printf("%v: receive is %s\n", time.Now(), rep.Name)
	reply := &pb.HelloReply{Message: "hello world" + rep.Name}
	return reply, nil
}

func main() {
	flag.Parse()
	listen, err := net.Listen("tcp", fmt.Sprintf("0.0.0.0:%d", *port))
	if err != nil {
		panic(err)
	}
	err = discover.Register(*serv, "127.0.0.1", *port, *reg, 10*time.Second, 15)
	if err != nil {
		panic(err)
	}
	ch := make(chan os.Signal, 1)
	signal.Notify(ch, syscall.SIGTERM, syscall.SIGINT, syscall.SIGKILL, syscall.SIGHUP, syscall.SIGQUIT)
	go func() {
		s := <-ch
		log.Printf("receive signal %v", s)
		discover.UnRegister()
		os.Exit(1)
	}()
	log.Printf("starting hello service at %d", *port)
	s := grpc.NewServer()
	pb.RegisterGreeterServer(s, &Greeter{})
	s.Serve(listen)
}
